package com.tx.core.mybatis.handler;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.Map;

/**
 * <pre>
 * 功能简述: MapTypeHandler
 * </pre>
 *
 * @author PengQingyang
 * 创建时间 [2024/4/10]
 */
@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({Map.class})
public class MapTypeHandler extends BaseTypeHandler<Map<String, Object>> {

    private ObjectMapper mapper = new ObjectMapper();

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, String columnName) {
        try {
            String value = rs.getString(columnName);
            return mapper.readValue(value, Map.class);
        } catch (Exception e) {

        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            String value = rs.getString(columnIndex);
            return mapper.readValue(value, Map.class);
        } catch (Exception e) {

        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            String value = cs.getString(columnIndex);
            return mapper.readValue(value, Map.class);
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, Object> parameter, JdbcType jdbcType)
            throws SQLException{
        if (parameter == null) {
            ps.setNull(i, Types.VARCHAR);
        } else {
            ps.setString(i, JSON.toJSONString(parameter));

        }

    }
}
